package com.dw.provider.api;

import com.dw.common.bean.NetNode;
import com.dw.common.bean.ResourceBean;
import com.dw.common.configuration.Configuration;
import com.dw.common.mapper.ResourceMapper;
import com.dw.common.service.KVService;
import com.dw.common.service.impl.KVServiceImpl;
import com.dw.provider.ProviderGrpc;
import com.dw.provider.Sender;
import com.dw.resource.GetResourceResponse;
import com.dw.resource.ResourceInfo;
import com.google.protobuf.ByteString;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import io.grpc.stub.StreamObserver;

import java.io.IOException;

public class ProviderImpl extends ProviderGrpc.ProviderImplBase {
    private final NetNode netNode;
    private final KVService kvService;

    public ProviderImpl(NetNode netNode) {
        this.netNode = netNode;
        kvService = new KVServiceImpl();
    }

    @Override
    public void getResource(ResourceInfo request, StreamObserver<GetResourceResponse> responseObserver) {
        ResourceBean resourceBean = ResourceMapper.resourceInfoToResourceBean(request);
        try {
            netNode.addCount();
            kvService.putWithLease(Configuration.UUID, netNode);
            Sender sender = new Sender(resourceBean);
            GetResourceResponse response = GetResourceResponse.newBuilder()
                    .setHeader(request)
                    .setBody(ByteString.copyFrom(sender.getSendBytes()))
                    .build();
            responseObserver.onNext(response);
            responseObserver.onCompleted();
            netNode.completeCount();
            kvService.putWithLease(Configuration.UUID, netNode);
        } catch (IOException e) {
            throw new StatusRuntimeException(Status.DATA_LOSS);
        }
    }

}
